import { createVuePlugin } from "vite-plugin-vue2";
import ViteComponents, {
  ElementUiResolver,
} from "vite-plugin-components";
import { defineConfig } from "vite";
import { viteCommonjs } from "@originjs/vite-plugin-commonjs";
import ScriptSetup from 'unplugin-vue2-script-setup/vite'
import viteCompression from 'vite-plugin-compression';
import styleImport from 'vite-plugin-style-import'
import { svgBuilder } from './src/utils/svg-builder';
import path from "path";
// import vitePluginImport from "vite-plugin-babel-import";
// 压缩代码配置
const compressPlugins = viteCompression({
  ext:'.gz',
  algorithm: 'gzip',
  threshold: 10240,
  deleteOriginFile: false,
  filter: new RegExp(
      '\\.(' + ['js'].join('|') +
      ')$'
  ),

})
//  配置组件库的样式 按需加载
const uiComponentPlugins = styleImport({
  libs:[
    {
      libraryName: 'element-ui',
      base: 'element-ui/lib/theme-chalk/base.css',
      resolveStyle: (name) => {
        return `element-ui/lib/theme-chalk/${name}.css`;
      },
      resolveComponent: (name) => {
        return `element-ui/lib/${name}`;
      },

    }
  ]
})
export default defineConfig({

  // 配置别名
  resolve: {
    alias: [
      {
        find: /^~/,
        replacement: "",
      },
      {
        find: "@",
        replacement: path.resolve(__dirname, "src"),
      },
    ],
  },
  css: {
    // css预处理器
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
      scss: {
        // 引入 var.scss 这样就可以在全局中使用 var.scss中预定义的变量了
        additionalData: `
                @import "./src/assets/style/common.scss";
                @import "./src/assets/style/mixin.scss";
                @import "./src/assets/style/reset.scss";
                @import "./src/assets/style/variable.scss";
                `
      }
    }
  },
  build: {
    terserOptions: {
      //  生产环境移除 console debugger
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
  },
  plugins: [
    //参考： https://juejin.cn/post/6973928601523585055
    createVuePlugin({
      jsx: true,
    }),
    compressPlugins,
    uiComponentPlugins,
    ScriptSetup({ /* options */ }),
    viteCommonjs(),
    svgBuilder('./src/assets/icon/'),
    //jsx和render函数按需加载
    // vitePluginImport([
    //   {
    //     libraryName: "view-design",
    //     libraryDirectory: "src/components",
    //     style(name) {
    //       return `view-design/dist/styles/iview.css`;
    //     },
    //     ignoreStyles: [],
    //   },
    // ]),

    //template自动按需加载
    ViteComponents({
      dirs: ["src/views"],
      // globalComponentsDeclaration: true,
      customComponentResolvers: [
        ElementUiResolver(),

      ],
    }),
  ],
});
